/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author TuanND
 */
public class PercolationStats {

    private double[] thresholds;
    private int N;
    private int T;

    public PercolationStats(int N, int T) // perform T independent computational experiments on an N-by-N grid
    {
        this.N = N;
        this.T = T;
        thresholds = new double[T];
        long seed = System.currentTimeMillis();
        StdRandom.setSeed(seed);
        for (int i = 0; i < T; i++) {
            System.out.println(i);
            //Initialize all sites to be blocked.             
            int numOpen = 0;
            Percolation percolation = new Percolation(N);
            while (!percolation.percolates()) {
                int id = StdRandom.uniform(N * N);
                int row = (int) Math.floor(id / N);
                int col = id - row * N;
                if (!percolation.isOpen(row, col)) {
                    percolation.open(row, col);
                    //System.out.println("(" + String.valueOf(row) + "," + String.valueOf(col) + ")\n");
                    numOpen++;
                }
            }
            thresholds[i] = (double) numOpen / (N * N);
        }

    }

    public double mean() // sample mean of percolation threshold
    {
        return StdStats.mean(thresholds);
    }

    public double stddev() // sample standard deviation of percolation threshold
    {
        return StdStats.stddevp(thresholds);
    }

    public double confidenceLo() // returns lower bound of the 95% confidence interval
    {
        return (mean() - 1.96 * stddev() / Math.sqrt(T));
    }

    public double confidenceHi() // returns upper bound of the 95% confidence interval
    {
        return (mean() + 1.96 * stddev() / Math.sqrt(T));
    }

    public static void main(String[] args) // test client, described below
    {
        int N = Integer.valueOf(args[0]);
        int T = Integer.valueOf(args[1]);
        PercolationStats percolationStats = new PercolationStats(N, T);
        System.out.printf("PercolationStats %d %d \n", N, T);
        System.out.printf("mean                    = %f\n", percolationStats.mean());
        System.out.printf("stddev                  = %f\n", percolationStats.stddev());
        System.out.printf("95 confidence interval = %f, %f\n", percolationStats.confidenceLo(), percolationStats.confidenceHi());
    }
}
